package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.SqlSessionUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserServiceImpl implements UserService {


    @Override
    public List<User> findAll() {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);

        return ud.findAll();
    }

    @Override
    public void add(User user) {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        ud.add(user);
        session.commit();
        session.close();
    }

    @Override
    public User ById(String id) {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        return ud.ById(id);
    }

    @Override
    public void update(User user) {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        ud.update(user);
        session.commit();
        session.close();
    }

    @Override
    public void delete(String id) {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        ud.delete(id);
        session.commit();
        session.close();

    }

    @Override
    public void deleteSelected(String[] uids) {
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        if(uids!=null){
            for (String uid : uids) {
                ud.delete(uid);
            }
        }
        session.commit();
        session.close();
    }

    @Override
    public PageInfo findByPage(String currentPageStr, String pageSizeStr) {
        //处理分页参数  可能为 null a  你好 等非数字类型字符串
        int currentPage=1;
        try {
            currentPage = Integer.parseInt(currentPageStr);
        } catch (NumberFormatException e) {
        }

        int pageSize=5;
        try {
            pageSize = Integer.parseInt(pageSizeStr);
        } catch (NumberFormatException e) {
        }
        //1. 设置分页查询参数
        PageHelper.startPage(currentPage,pageSize);
        //2 查询分页集合
        SqlSession session=SqlSessionUtils.getSqlSession();
        UserDao ud = session.getMapper(UserDao.class);
        List<User> list = ud.findAll();
        //3. 封装PageInfo
        PageInfo<User> pageInfo=new PageInfo<>(list);

        return pageInfo;
    }
}
